package com.project.les.view.adapters;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.project.les.R;
import com.project.les.ViewFeriadoActivity;
import com.project.les.view.elements.FeriadoViewElement;
import com.project.les.view.elements.StateViewElement;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class StateListAdapter extends BaseExpandableListAdapter {
	
	// Variáveis do parent:
	//private List<? extends Map<String, ?>> mGroupData;
	private List<Map<String, String>> mGroupData = new ArrayList<Map<String, String>>();
	private int mExpandedGroupLayout;
	private int mCollapsedGroupLayout;
	private String[] mGroupFrom;
	private int[] mGroupTo;
	
	//private List<? extends List<? extends Map<String, ?>>> mChildData;
	private List<List<Map<String, String>>> mChildData = new ArrayList<List<Map<String, String>>>();
	private int mChildLayout;
	private int mLastChildLayout;
	private String[] mChildFrom;
	private int[] mChildTo;
	
	private LayoutInflater mInflater;
	
	private String firstElement;
	private String lastElement;
	
	
	// Variáveis desta classe:
	private Context context;
	private List<StateViewElement> elementList;

	private static final String KEYID = "ID";
	private static final String KEY1 = "MENU";
	private static final String KEY2 = "SUBMENU";
	
	private String[] states;
	private String[][][] feriadosStates;
	
	//private List<Map<String, String>> mGroupData = new ArrayList<Map<String, String>>();
	//private List<List<Map<String, String>>> mChildData = new ArrayList<List<Map<String, String>>>();

	
	
	public StateListAdapter(Context context, List<StateViewElement> elementList) {
		
		this.context = context;
		this.elementList = elementList;
		
		this.loadStatesList();
		this.prepareMenuAndChildData();
		
		mExpandedGroupLayout = android.R.layout.simple_expandable_list_item_1;
		mCollapsedGroupLayout = android.R.layout.simple_expandable_list_item_1;
		mGroupFrom = new String[] {
			KEYID,
			KEY1,
			KEY2
		};
		mGroupTo = new int[] {
			R.id.tvRegId,
			android.R.id.text1,
			android.R.id.text2
		};

		mChildLayout = R.layout.simple_expandable_list_item_2_with_id;
		mLastChildLayout = R.layout.simple_expandable_list_item_2_with_id;
		mChildFrom = new String[] {
				KEYID,
				KEY1,
				KEY2
			};
		mChildTo = new int[] {
				R.id.tvRegId,
				android.R.id.text1,
				android.R.id.text2
			};

		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	
	private void prepareMenuAndChildData() {
		for (int i = 0; i < states.length; i++) {
			Map<String, String> curMenuMap = new HashMap<String, String>();
			mGroupData.add(curMenuMap);
			curMenuMap.put(KEY1, states[i]);
			curMenuMap.put(KEY2, "");
	
			List<Map<String, String>> subMenu = new ArrayList<Map<String, String>>();
			if (feriadosStates.length > i) {
				for (int j = 0; j < feriadosStates[i].length; j++) {
					Map<String, String> curSubMenuMap = new HashMap<String, String>();
					subMenu.add(curSubMenuMap);
					curSubMenuMap.put(KEYID, feriadosStates[i][j][0]);
					curSubMenuMap.put(KEY1, feriadosStates[i][j][1]);
					curSubMenuMap.put(KEY2, feriadosStates[i][j][2]);
				}
			}
			mChildData.add(subMenu);
		}
	}

	/**
	 * Inicializa a variável de lista de estados e a de classe de
	 * lista de feriados por estados que deve ser no formato abaixo:
	 * {
	 *  	{
	 *  		{ "SUBMENU 11", "TEXTO 11" }
	 *  	},
	 *  	{
	 *  		{ "SUBMENU 21", "TEXTO 21" },
	 *  		{ "SUBMENU 22", "TEXTO 22" }
	 *  	},
	 *  	{
	 *  		{ "SUBMENU 31", "TEXTO 31" },
	 *  		{ "SUBMENU 32", "TEXTO 32" },
	 *  		{ "SUBMENU 33", "TEXTO 33" }
	 *  	}
	 * };
	 */
	private void loadStatesList() {

		ArrayList<String> listStates = new ArrayList<String>();
		ArrayList<String[][]> listFeriados = new ArrayList<String[][]>();
		String[][] feriados = null;
		StateViewElement aux;
		
		Iterator<StateViewElement> it = this.elementList.iterator();
		Iterator<FeriadoViewElement> itFeriados;
		int i;
		while (it.hasNext()) {
			aux = it.next();
			
			listStates.add(aux.getName());
			feriados = new String[aux.getNumberOfFeriados()][3];
			itFeriados = aux.getFeriadosIterator();
			FeriadoViewElement feriadoAux;
			i = 0;
			while (itFeriados.hasNext()) {
				feriadoAux = itFeriados.next();
				feriados[i][0] = String.valueOf(feriadoAux.getId());
				feriados[i][1] = feriadoAux.getName();
				feriados[i][2] =
					String.valueOf(feriadoAux.getDay()) + "/" 
					+ String.valueOf(feriadoAux.getMonth()) + "/"
					+ String.valueOf(feriadoAux.getYear())
				;
				i++;
			}
			
			listFeriados.add(feriados);
		}
		
		this.states = new String[listStates.size()];
		this.feriadosStates = new String[listFeriados.size()][][];
		for (i = 0; i < listStates.size(); i++) {
			this.states[i] = listStates.get(i);
			this.feriadosStates[i] = listFeriados.get(i);
		}
		
	}
	
	
	// Métodos da classe SimpleExpandableListAdapter (código original do Android)
	
	//@Override
	public Object getChild(int groupPosition, int childPosition) {
		return mChildData.get(groupPosition).get(childPosition);
	}

	//@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	//@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		View v;
		if (convertView == null) {
			v = newChildView(isLastChild, parent);
		} else {
			v = convertView;
		}
		bindView(v, mChildData.get(groupPosition).get(childPosition),
				mChildFrom, mChildTo);
		
		return v;
	}

	/**
	 * Instantiates a new View for a child.
	 * @param isLastChild Whether the child is the last child within its group.
	 * @param parent The eventual parent of this new View.
	 * @return A new child View
	 */
	public View newChildView(boolean isLastChild, ViewGroup parent) {
		return mInflater.inflate((isLastChild) ? mLastChildLayout
				: mChildLayout, parent, false);
	}

	private void bindView(View view, Map<String, ?> data,
			String[] from, int[] to) {
		int len = to.length;
		
		/* 
		 * Aqui o Map data pode ter dois valores possíveis:
		 * {MENU=NomeEstado, SUBMENU=}
		 * ou
		 * {ID=00, MENU=NomeFeriado, SUBMENU=}
		 * 
		 * Na presente situação, o layout padrão do Android foi trocado por
		 * um que tem um TextView oculto (visibility="gone").
		 * 
		 * Esta função aqui é baseada no código original do Android para
		 * SimpleExpandableListAdapter e executa para cada item do registro.
		 * 
		 * O loop abaixo executa para cada um dos itens de data, ou seja,
		 * dependendo de qual dos dois "data" acima representados aparecem
		 * aqui, o loop executa uma quantidade de vezes diferente (2 e 3 vezes,
		 * respectivamente). O loop preenche cada um dos TextView do layout,
		 * preenchendo, também, o textView de ID que está oculto. 
		 */
		for (int i = 0; i < len; i++) {
			TextView v = (TextView) view.findViewById(to[i]);
			if (v != null) {
				
				// Se tvRegId existe, é porque temos um feriado, e não um estado.
				// Se sobrescrevermos o clique nos estados o sistema de expansão da view para de funcionar.
				
				TextView tvRegId = (TextView) v.findViewById(R.id.tvRegId);
				
				if (tvRegId != null) {
					
					view.setOnTouchListener(new OnTouchListener() {
						
						// @Override
						public boolean onTouch(View v, MotionEvent event) {
							if (event.getAction() == MotionEvent.ACTION_UP) {
								Intent i = new Intent(v.getContext(),
										ViewFeriadoActivity.class);
								
								TextView tvRegId = (TextView) v.findViewById(R.id.tvRegId);
								
								Integer regId = Integer.valueOf(tvRegId.getText()
										.toString());
								
								i.putExtra("id", regId);
								v.getContext().startActivity(i);
							}
							return true;
						}
					});
					
					//v.setTypeface(Typeface.DEFAULT);
					
				} else {
					//v.setTypeface(Typeface.DEFAULT_BOLD);
				}
				
				v.setText((String) data.get(from[i]));
				v.setTextColor(Color.parseColor("#000000"));
			}
		}
		
					
		
	}

	//@Override
	public int getChildrenCount(int groupPosition) {
		return mChildData.get(groupPosition).size();
	}

	//@Override
	public Object getGroup(int groupPosition) {
		return mGroupData.get(groupPosition);
	}

	//@Override
	public int getGroupCount() {
		return mGroupData.size();
	}

	//@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	//@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		View v;
		if (convertView == null) {
			v = newGroupView(isExpanded, parent);
		} else {
			v = convertView;
		}
		
		bindView(v, mGroupData.get(groupPosition), mGroupFrom, mGroupTo);
		return v;
	}

	/**
	 * Instantiates a new View for a group.
	 * @param isExpanded Whether the group is currently expanded.
	 * @param parent The eventual parent of this new View.
	 * @return A new group View
	 */
	public View newGroupView(boolean isExpanded, ViewGroup parent) {
		return mInflater.inflate((isExpanded) ? mExpandedGroupLayout
				: mCollapsedGroupLayout, parent, false);
	}

	//@Override
	public boolean isChildSelectable(int groupPosition,
			int childPosition) {
		return true;
	}

	//@Override
	public boolean hasStableIds() {
		return true;
	}
	
	
}